<template>
  <div>
    <div style="width: 600px; padding: 30px 60px; margin: 50px auto; background: #fff;">
      <h1 style="text-align: center; margin: 0 0 30px 0;">管理员登录</h1>
      <el-form :rules="rules" ref="form" :model="form" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('form')">登录</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: 'root',
        password: '123456'
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 4, max: 15, message: '用户名的长度必须是4至15个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:9081/admins/login';
          console.log('请求路径：' + url);
          console.log('请求参数：');
          console.log(this.form);
          let formData = this.qs.stringify(this.form);
          this.axios.post(url, formData).then((response) => {
            console.log('服务器端的响应：');
            console.log(response);
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              // 登录成功，服务器端将响应JWT
              let jwt = responseBody.data;
              console.log('登录成功，服务器端响应的JWT：' + jwt);
              // 使用LocalStorage存储JWT
              localStorage.setItem('jwt', jwt);
              console.log('将JWT数据保存到LocalStorage！');
              // 测试：从LocalStorage中取出JWT
              let localJwt = localStorage.getItem('jwt');
              console.log('测试：从LocalStorage中取出JWT：' + localJwt);
              // 提示
              this.$message({
                message: '登录成功！',
                type: 'success'
              });
              // 跳转页面
              this.$router.push('/');
            } else {
              // 用户名或密码错误、账号被禁用
              this.$message.error(responseBody.message);
            }
          });
        } else {
          alert('参数格式有误，不允许提交！');
          return false;
        }
      });
    }
  }
}
</script>

<style>
body {
  background: #12487d !important;
}
</style>